package com.Lacia.emsserver.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @author Albert Chen
 */
@Slf4j
public class MqttMessageCallback implements MqttCallback {

    private final MqttClient mqttClient;
//    private final DataService dataService;
    private final MqttConnection connection;

    private Boolean isReconnecting = false;

    public MqttMessageCallback(MqttClient mqttClient,  MqttConnection connection) {
        this.mqttClient = mqttClient;
        this.connection = connection;
    }

    @Override
    public void connectionLost(Throwable cause) {
        log.error("Mqtt connection lost", cause);

        if (isReconnecting) {
            return;
        }
        isReconnecting = true;
        Thread thread = new Thread(() -> {
            log.info("Waiting for mqtt client to connect...");
            while (!mqttClient.isConnected()) {
                try {
                    Thread.sleep(1000);
                    log.info("Waiting for mqtt client to connect...");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            connection.subscribeAllEmsTopic();
            isReconnecting = false;
        });
        thread.start();

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.debug("Mqtt message arrived, topic: {}, message: {}", topic, message.toString());
//        dataService.handleData(topic, message.toString(), "mqtt");
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {}

}
